package com.zbf1811a.mqlistener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/7/27  17:25
 * 描述: 消费消息的Listener
 */
@Component
@RabbitListener(queues = {"REDIS-QUEUE"})
public class My11AMqListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitHandler
    public void handler(Object msg, Message message, Channel channel) throws IOException {

        //消费消息
        try{
            //1获取消息
            String str=new String(message.getBody(),Charset.forName("utf-8"));
            //2将消息转为JSON对象
            JSONObject jsonObject = JSON.parseObject(str);

            System.out.println("接收到的消息："+str);
            //3业务处理 第二次删除redis中的Key
            redisTemplate.delete(jsonObject.get("key").toString());

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){

            //插入消息表
            //重新入队
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }





    }

}
